package com.tanhua.server.serivce;

import com.alibaba.fastjson.JSON;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Voice;
import com.tanhua.domain.vo.VoiceVo;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.VoiceApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class PeachService {
    @Reference
    private VoiceApi voiceApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Autowired
    private FastFileStorageClient storageClient;
    @Autowired
    private FdfsWebServer fdfsWebServer;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public static final String VOICE_KEY = "VOICE_";

    public ResponseEntity<Object> sendVoice(MultipartFile soundFile) throws IOException {
        //得到url地址
        String originalFilename = soundFile.getOriginalFilename();
        String ext = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        StorePath storePath = storageClient.uploadFile(soundFile.getInputStream(), soundFile.getSize(), ext, null);
        String voiceUrl  = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();

        //封装存入mongo
        Voice voice = new Voice();
        voice.setId(ObjectId.get());
        Long userId = UserHolder.getUserId();
        voice.setUserId(userId);
        UserInfo userInfo = userInfoApi.findById(userId);
        voice.setGender(userInfo.getGender());
        voice.setAge(userInfo.getAge());
        voice.setSoundUrl(voiceUrl);
        voice.setCreated(System.currentTimeMillis());
        voiceApi.save(voice);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity<Object> acceptVoice() {
        Long userId = UserHolder.getUserId();
        //存储次数到redis，先查询redis，没有查询到，为用户设置默认语言次数，查询到，直接获取语言次数
        String countStr = redisTemplate.opsForValue().get("SOUND_RECEIVE_COUNT_" + userId);
        Integer count = 0;

        if(StringUtils.isEmpty(countStr)){
            count = 11;
            redisTemplate.opsForValue().set("SOUND_RECEIVE_COUNT_" + userId,count.toString(),getTime(),TimeUnit.MILLISECONDS);
        }else{
            count = Integer.valueOf(countStr);
        }
        if (count == 0) {
            return null;
        }

        String gender = userInfoApi.findById(userId).getGender();
        Voice voice = null;
        String key = VOICE_KEY + userId;

        //redis查询语言列表 不存在登录用户的语言列表，获取mongo数据库列表，存入redis
        //存在登录用户语言列表，获取一条语言
        if(!redisTemplate.hasKey(key)){
            List<Voice> voiceList = voiceApi.findVoice(userId,gender);
            voice = getVoice(key, voiceList);
        }else{
            String voices = redisTemplate.opsForValue().get(key);
            List<Voice> voiceList = JSON.parseArray(voices,Voice.class);
            if(CollectionUtils.isEmpty(voiceList)){
                voiceList = voiceApi.findVoice(userId,gender);
                voice = getVoice(key,voiceList);
            }else{
                voice = getVoice(key,voiceList);
            }
        }
        Integer remainingTimes = count - 1;
        redisTemplate.opsForValue().set("SOUND_RECEIVE_COUNT_" + userId,remainingTimes.toString(),getTime(),TimeUnit.MILLISECONDS);

        //封装返回结果
        UserInfo userInfo = userInfoApi.findById(voice.getUserId());
        VoiceVo voiceVo = new VoiceVo();
        voiceVo.setId(userInfo.getId().intValue());
        voiceVo.setAvatar(userInfo.getAvatar());
        voiceVo.setNickname(userInfo.getNickname());
        voiceVo.setGender(userInfo.getGender());
        voiceVo.setAge(userInfo.getAge());
        voiceVo.setSoundUrl(voice.getSoundUrl());
        voiceVo.setRemainingTimes(remainingTimes);
        return ResponseEntity.ok(voiceVo);
    }
    //计算当前时间到零点时间的毫秒值
    private long getTime(){
        long zero = LocalDateTime.of(LocalDate.now(), LocalTime.MAX).toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
        return (zero - System.currentTimeMillis());
    }
    //取语言
    private Voice getVoice(String key,List<Voice> voiceList){
        Voice voice = voiceList.remove(RandomUtils.nextInt(0,voiceList.size()));
        redisTemplate.opsForValue().set(key, JSON.toJSONString(voiceList));
        return voice;
    }
}
